//
//  GatherSetting.m
//  YYTextTest
//
//  Created by macintosh on 16/9/12.
//  Copyright © 2016年 macintosh. All rights reserved.
//

#import "GatherSetting.h"
#import "GatherSegmentCell.h"
#import "GatherIndicatorCell.h"
#import "GatherPickerCell.h"
#import "YYCGUtilities.h"
#import "GatherInfo.h"
#import "InfoArchiver.h"

@interface GatherSetting () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, assign) NSInteger openedRow;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) GatherInfo *gatherInfo;

@end

@implementation GatherSetting

+ (instancetype)gatherSettingWithGatherInfo:(GatherInfo *)gatherInfo
{
    GatherSetting *gatherSetting = [GatherSetting new];
    gatherSetting.gatherInfo = gatherInfo;
    return gatherSetting;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configGatherSetting];
    [self configGoBackButton];
    [self initTableView];
    [self initDatas];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(segmentStateDidChanged:) name:GatherSegmentCellSegmentSelectedNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)configGatherSetting
{
    [self.navigationController setNavigationBarHidden:NO];
    self.title = @"设置";
    self.view.backgroundColor = ColorRGB(247, 247, 249);
}

- (void)configGoBackButton
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"chevron_left"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(goBack:)];
}

- (void)goBack:(UIBarButtonItem *)barBtn
{
    [self archiveDatas:_datas];
    
    if (_goBack) {
        _goBack([self fetchGatherInfo]);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initTableView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    tableView.backgroundColor = self.view.backgroundColor;
    tableView.delegate = self;
    tableView.dataSource = self;
    
    [tableView registerClass:[GatherSegmentCell class] forCellReuseIdentifier:@"GatherSegmentCell"];
    [tableView registerClass:[GatherIndicatorCell class] forCellReuseIdentifier:@"GatherIndicatorCell"];
    [tableView registerClass:[GatherPickerCell class] forCellReuseIdentifier:@"GatherPickerCell"];
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    _tableView = tableView;
    [self.view addSubview:tableView];
}

- (void)initDatas
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        _datas = [[self unarchiveDatas] mutableCopy];
        
        if (!_gatherInfo) {
            _gatherInfo = [GatherInfo defaultGatherInfo];
        }
        
        if (!_datas) {
            _datas = [NSMutableArray array];
            
            GatherSegmentInfo *segment1 = [GatherSegmentInfo infoWithTitle:@"台标" items:@[@"开", @"关"] firstSelected:_gatherInfo.showLogo enabled:YES];
            [_datas addObject:segment1];
            GatherSegmentInfo *segment2 = [GatherSegmentInfo infoWithTitle:@"摄像头" items:@[@"前", @"后"] firstSelected:_gatherInfo.isFrontCamera enabled:YES];
            [_datas addObject:segment2];
            GatherSegmentInfo *segment3 = [GatherSegmentInfo infoWithTitle:@"弹幕" items:@[@"开", @"关"] firstSelected:_gatherInfo.showBarrage enabled:YES];
            [_datas addObject:segment3];
            GatherSegmentInfo *segment4 = [GatherSegmentInfo infoWithTitle:@"背光灯" items:@[@"开", @"关"] firstSelected:_gatherInfo.openTorch enabled:_gatherInfo.isFrontCamera ? NO : YES];
            [_datas addObject:segment4];
            GatherSegmentInfo *segment5 = [GatherSegmentInfo infoWithTitle:@"美颜" items:@[@"开", @"关"] firstSelected:_gatherInfo.openBeauty enabled:YES];
            [_datas addObject:segment5];
            GatherSegmentInfo *segment6 = [GatherSegmentInfo infoWithTitle:@"屏幕模式" items:@[@"横", @"竖"] firstSelected:_gatherInfo.isLandscape enabled:YES];
            [_datas addObject:segment6];
            
            NSArray *pickerDatas1 = @[@"720P", @"1080P"];
            GatherIndicatorInfo *indicator1 = [GatherIndicatorInfo infoWithTitle:@"分辨率" detailTitle:pickerDatas1[0] pickerDatas:pickerDatas1 selectedIndex:0 isOpened:NO];
            [_datas addObject:indicator1];
            
            NSArray *pickerDatas2 = @[@"32Kbps", @"64Kbps", @"96Kbps", @"128Kbps"];
            GatherIndicatorInfo *indicator2 = [GatherIndicatorInfo infoWithTitle:@"音频码率" detailTitle:pickerDatas2[3] pickerDatas:pickerDatas2 selectedIndex:3 isOpened:NO];
            [_datas addObject:indicator2];
            
            NSArray *pickerDatas3 = @[@"800Kbps", @"1000Kbps", @"1200Kbps", @"1400Kbps", @"1600Kbps", @"1800Kbps", @"2000Kbps", @"2400Kbps", @"3000Kbps", @"4000Kbps"];
            GatherIndicatorInfo *indicator3 = [GatherIndicatorInfo infoWithTitle:@"视频码率" detailTitle:pickerDatas3[3] pickerDatas:pickerDatas3 selectedIndex:3 isOpened:NO];
            [_datas addObject:indicator3];
            
            NSArray *pickerDatas4 = @[@"15Fps", @"20Fps", @"25Fps", @"30Fps"];
            GatherIndicatorInfo *indicator4 = [GatherIndicatorInfo infoWithTitle:@"视频码率" detailTitle:pickerDatas4[2] pickerDatas:pickerDatas4 selectedIndex:1 isOpened:NO];
            [_datas addObject:indicator4];
        } else {
            GatherSegmentInfo *segment = _datas[0];
            segment.firstSelected = _gatherInfo.showLogo;
            
            segment = _datas[1];
            segment.firstSelected = _gatherInfo.isFrontCamera;
            
            segment = _datas[2];
            segment.firstSelected = _gatherInfo.showBarrage;
            
            segment = _datas[3];
            if (_gatherInfo.isFrontCamera) {
                segment.firstSelected = NO;
                segment.enabled = NO;
            } else {
                segment.firstSelected = _gatherInfo.openTorch;
                segment.enabled = YES;
            }
    
            segment = _datas[4];
            segment.firstSelected = _gatherInfo.openBeauty;

            segment = _datas[5];
            segment.firstSelected = _gatherInfo.isLandscape;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
        });
    });
}

- (void)removeNullDatas
{
    __block NSMutableIndexSet *removeArr = [NSMutableIndexSet indexSet];
    [_datas enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[GatherIndicatorInfo class]]) {
            [(GatherIndicatorInfo *)obj setIsOpened:NO];
        }
        
        if ([obj isKindOfClass:[NSNull class]]) {
            [removeArr addIndex:idx];
        }
    }];
    [_datas removeObjectsAtIndexes:removeArr];
}

- (NSString *)gatherSettingArchiverPath
{
    return [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"gatherSetting.archiver"];
}

- (void)archiveDatas:(id)datas
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self removeNullDatas];
        [InfoArchiver archiveRootObject:_datas toFile:[self gatherSettingArchiverPath]];
    });
}

- (id)unarchiveDatas
{
    return [InfoUnarchiver unarchiveObjectWithFile:[self gatherSettingArchiverPath]];
}

- (GatherInfo *)fetchGatherInfo
{
    [self removeNullDatas];
    
    GatherInfo *info = [GatherInfo new];
    info.showLogo = [(GatherSegmentInfo *)_datas[0] firstSelected];
    info.isFrontCamera = [(GatherSegmentInfo *)_datas[1] firstSelected];
    info.showBarrage = [(GatherSegmentInfo *)_datas[2] firstSelected];
    info.openTorch = [(GatherSegmentInfo *)_datas[3] firstSelected];
    info.openBeauty = [(GatherSegmentInfo *)_datas[4] firstSelected];
    info.isLandscape = [(GatherSegmentInfo *)_datas[5] firstSelected];
    info.resolution = integerFromString([(GatherIndicatorInfo *)_datas[6] detailTitle]);
    info.audioRate = integerFromString([(GatherIndicatorInfo *)_datas[7] detailTitle]);
    info.videoRate = integerFromString([(GatherIndicatorInfo *)_datas[8] detailTitle]);
    info.fps = (float)integerFromString([(GatherIndicatorInfo *)_datas[9] detailTitle]);
    
    [GatherInfo archiveGatherInfo:info];
    
    return info;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section == 0 ? (_datas.count ? _datas.count : 0) : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (indexPath.section == 1) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
        cell.textLabel.text = @"登出";
        return cell;
    }
    
    if ([_datas[indexPath.row] isKindOfClass:[GatherSegmentInfo class]]) {
        GatherSegmentCell *segmentCell = [tableView dequeueReusableCellWithIdentifier:@"GatherSegmentCell"];
        segmentCell.indexPath = indexPath;
        segmentCell.info = _datas[indexPath.row];
        cell = segmentCell;
    } else if ([_datas[indexPath.row] isKindOfClass:[GatherIndicatorInfo class]]) {
        GatherIndicatorCell *indicatorCell = [tableView dequeueReusableCellWithIdentifier:@"GatherIndicatorCell"];
        indicatorCell.info = _datas[indexPath.row];
        cell = indicatorCell;
    } else if ([_datas[indexPath.row] isKindOfClass:[NSNull class]]) {
        GatherPickerCell *pickerCell = [tableView dequeueReusableCellWithIdentifier:@"GatherPickerCell"];
        pickerCell.pickerDatas = [(GatherIndicatorInfo *)_datas[indexPath.row - 1] pickerDatas];
        pickerCell.selectedRow = [(GatherIndicatorInfo *)_datas[indexPath.row - 1] selectedIndex];
        
        __weak typeof(self) weakSelf = self;
        pickerCell.pickerSelected = ^(NSInteger row) {
            GatherIndicatorInfo *info = weakSelf.datas[weakSelf.openedRow];
            info.selectedIndex = row;
            info.detailTitle = info.pickerDatas[row];
            [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        };
        
        cell = pickerCell;
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    view.tintColor = [UIColor clearColor];
}

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = [UIColor clearColor];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_datas[indexPath.row] isKindOfClass:[NSNull class]]) {
        return 100;
    } else {
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (indexPath.section == 1) {
        [self archiveDatas:_datas];
        //登出
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    if ([_datas[indexPath.row] isKindOfClass:[GatherSegmentInfo class]]) {
        return;
    }
    
    if ([_datas[indexPath.row] isKindOfClass:[NSNull class]]) {
        return;
    }
    
    if ([_datas[indexPath.row] isKindOfClass:[GatherIndicatorInfo class]]) {
        GatherIndicatorInfo *info = _datas[indexPath.row];
        info.isOpened = !info.isOpened;
        
        [tableView beginUpdates];
        if (info.isOpened) {
            if (_openedRow > 0) {
                [_datas removeObjectAtIndex:_openedRow + 1];
                [tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:_openedRow + 1 inSection:0]] withRowAnimation:UITableViewRowAnimationMiddle];
                [(GatherIndicatorInfo *)_datas[_openedRow] setIsOpened:NO];
                if (_openedRow > indexPath.row) {
                    _openedRow = indexPath.row;
                } else {
                    _openedRow = indexPath.row - 1;
                }
            } else {
                _openedRow = indexPath.row;
            }
            
            [_datas insertObject:[NSNull null] atIndex:_openedRow + 1];
            [tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:_openedRow + 1 inSection:0]] withRowAnimation:UITableViewRowAnimationMiddle];
        } else {
            [_datas removeObjectAtIndex:indexPath.row + 1];
            [tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0]] withRowAnimation:UITableViewRowAnimationMiddle];
            _openedRow = -1;
        }
        [tableView endUpdates];
    }
}

#pragma mark - notification

- (void)segmentStateDidChanged:(NSNotification *)noti
{
    NSIndexPath *indexPath = noti.userInfo[@"indexPath"];
    BOOL firstSelected = [noti.userInfo[@"firstSelected"] boolValue];
    if (indexPath.row == 1) {
        GatherSegmentInfo *info = _datas[3];
        info.enabled = !firstSelected;
        if (firstSelected) {
            info.firstSelected = NO;
        }
        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    }
}

@end
